// pages/cardHolder/cardHolder.js
var app = getApp();
const port = require('../../config.js');
const mainIndex = require('../index.js');
const vipPrivilege = require('../../common/vipPrivilege.js');
const judgeVip = require('../../common/judgeVip.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    run: 0,
    addshow: false,
    src: '',
    scanData: [],
    holderCheck: 1, //判断是否第一次进入
    prompt: 1,
    indexShuttle: mainIndex.indexShuttle, //跳转分包shuttle统一路径
    indexMessage: mainIndex.indexMessage, //跳转分包message统一路径
    indexCenter: mainIndex.indexCenter, //跳转分包center统一路径
    whefixed: 'fixed', //是否使搜索框为fixed
    zIndex: 999, //head初始化层级
    zAddIndex: 999, //搜索框初始化层级
    zSeaIndex: 999, //添加名片初始化层级
    vipTip: false, //是否需要提示成为会员
    vipTipContent: '', //成为会员弹窗提示内容
    tipknow: false, //弹窗提示
    showDeduct: false, //扣除积分弹窗
    nomoreTipImg: '/images/btn_choose_normal@3x.png', //不再提醒图标
    nomoreTip: false, //设置不再提醒
    deductType: 'make', //添加名片方式make：手动   scan：扫描
    cid: '', //用户cid
    zimuList: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"], //右侧选择器
    whiceGroup: "A", //默认选择器元素
    lastX: 0,
    lastY: 0,
    currentGesture: 0,
    startLeftRun: 0, //向左滑动操作
    touchId: 0,
    askdelete: false, //询问删除弹窗
    friends_idDelete: '', //删除人的friends_id
    is_paperDelete: '' //删除人是否是纸质名片
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu();
    //判断是否首次进入
    var that = this;
    this.showAll();
    //判断是否设置不再提醒
    var holderdeduct = wx.getStorage({
      key: 'holderdeduct',
      success: function(res) {
        if (res.data == 0) {
          that.setData({
            holderdeduct: true //缓存判断true：应展示
          })
        } else if (res.data == 1) {
          that.setData({
            holderdeduct: false
          })
        }
      },
    })

  },
  //跳转会员中心
  vipCenter: function() {
    var that = this;
    var cid = that.data.cid
    if (!cid) {
      wx.showToast({
        icon: 'success',
        image: '/images/error.png',
        title: '请先添加名片',
      })
    } else {
      var indexShuttle = that.data.indexShuttle;
      wx.navigateTo({
        url: indexShuttle + '/vipCenter/vipCenter',
      })
    }
  },
  //询问删除弹窗
  askdelete: function(e) {
    var that = this;
    that.setData({
      askdelete: true,
      friends_idDelete: e.target.dataset.friends_id,
      is_paperDelete: e.target.dataset.is_paper,
    })
  },
  //取消删除
  canceldelete: function() {
    var that = this;
    that.setData({
      askdelete: false
    })
  },
  //删除咖片
  deleteCard: function(e) {
    var that = this;
    var is_paper = that.data.is_paperDelete; //0 好友名片  1 纸质名片
    var friends_id = that.data.friends_idDelete;
    app.getUserInfo(function(personInfo) {
      var openid = personInfo.openId;
      var token = personInfo.token;
      var uid = personInfo.uid;
      wx.showLoading({
        title: '删除中...',
      })
      if (is_paper == 0) {
        //解除好友关系
        wx.request({
          url: port.friendsdel, //请求地址
          header: { //请求头
            "Content-Type": "applciation/json",
            "Authorization": "Bearer " + token
          },
          data: {
            'friends_id': friends_id
          },
          method: "post", //get为默认方法/POST
          success: function(res) {
            if (res.data.status == 'success') {
              wx.hideLoading();
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              })
              that.setData({
                askdelete: false
              })
              setTimeout(function() {
                that.showAll()
              }, 1000)
            }
          },
          fail: function(err) {}, //请求失败
          complete: function(suc) { //请求完成后执行的函数
          }
        })
      } else if (is_paper == 1) {
        //删除纸质名片
        wx.request({
          url: port.paperdelete, //请求地址
          header: { //请求头
            "Content-Type": "applciation/json",
            "Authorization": "Bearer " + token
          },
          data: {
            'friends_id': friends_id
          },
          method: "post", //get为默认方法/POST
          success: function(res) {
            if (res.data.status == 'success') {
              wx.hideLoading();
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              })
              that.setData({
                askdelete: false
              })
              setTimeout(function() {
                that.showAll()
              }, 1000)
            }
          },
          fail: function(err) {}, //请求失败
          complete: function(suc) { //请求完成后执行的函数
          }
        })
      }
    })
  },
  //关闭扣除积分弹窗
  closeDeduct: function() {
    var that = this;
    that.setData({
      showDeduct: false
    })
    var nomoreTip = that.data.nomoreTip;
    if (nomoreTip) {
      wx.setStorage({
        key: 'holderdeduct',
        data: 1,
      })
      that.setData({
        holderdeduct: false
      })
    }
  },
  //切换不再提醒
  nomoreTip: function(option) {
    var that = this;
    var nomoreTip = option.target.dataset.nomoretip;
    var nomoreTipImg = that.data.nomoreTipImg;
    if (nomoreTip == false) {
      nomoreTip = true;
      nomoreTipImg = '/images/btn_choose_selected@3x.png'
    } else {
      nomoreTip = false;
      nomoreTipImg = '/images/btn_choose_normal@3x.png'
    }
    that.setData({
      nomoreTip: nomoreTip,
      nomoreTipImg: nomoreTipImg
    })
  },
  //关闭成为vip提示
  cancelVipTip: function() {
    var that = this;
    that.setData({
      vipTip: false,
      tipknow: false
    })
  },
  //下一步引导
  nextPrompt: function(e) {
    var that = this;
    var prompt = e.currentTarget.dataset.prompt;
    if (prompt == 1) {
      wx.setStorage({
        key: 'holderCheck',
        data: 1,
      })
    }
    that.setData({
      prompt: prompt
    })
    var holderCheck = wx.getStorage({
      key: 'holderCheck',
      success: function(res) {
        if (res.data == 0) {
          that.setData({
            holderCheck: 0,
          })
        } else if (res.data == 1) {
          that.setData({
            holderCheck: 1,
            zIndex: 999, //head初始化层级
            zAddIndex: 999, //搜索框初始化层级
            zSeaIndex: 999, //添加名片初始化层级
            whefixed: 'fixed'
          })
        }
      },
    })
  },

  //预览
  goView: function(e) {
    var that = this;
    var indexShuttle = that.data.indexShuttle
    wx.navigateTo({
      url: '/pages/index/preview?cid=' + e.currentTarget.id, //单击获取对应id
    })
  },
  //修改名片
  updatePaper: function(e) {
    var that = this;
    var indexMessage = that.data.indexMessage;
    wx.navigateTo({
      url: indexMessage + '/paperCard/paperCard?cid=' + e.currentTarget.id, //单击获取对应id
    })
  },
  //添加名片
  addCard: function() {
    var that = this;
    that.setData({
      addshow: !that.data.addshow,
    })
  },
  prevetadd: function(e) {
    e.stopPropagation;
  },
  //弹窗扣除积分，继续事件
  confirmLook: function() {
    var that = this;
    var deductType = that.data.deductType;
    if (deductType == 'make') {
      this.privilege(function(result) {
        if (result) {
          var indexMessage = that.data.indexMessage;
          wx.navigateTo({
            url: indexMessage + '/storeCard/storeCard',
          })
          that.setData({
            addshow:false,
          })
        }
      })
    } else if (deductType == 'scan') {
      that.scanCard();
    }
    var nomoreTip = that.data.nomoreTip;

    if (nomoreTip) {
      wx.setStorage({
        key: 'holderdeduct',
        data: 1,
      })
      that.setData({
        holderdeduct: false
      })
    }
    that.setData({
      showDeduct: false
    })
  },

  //手动添加名片
  makeCards: function() {
    var that = this;
    app.getUserInfo(function(personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      judgeVip.judgeVip(token, uid, function(result) {
        if (result) {
          that.privilege(function(result) {
            if (result) {
              var indexMessage = that.data.indexMessage;
              wx.navigateTo({
                url: indexMessage + '/storeCard/storeCard',
              })
              that.setData({
                addshow: false
              })
            }
          })
        } else {
          if (!that.data.holderdeduct) {
            that.privilege(function(result) {
              if (result) {
                var indexMessage = that.data.indexMessage;
                wx.navigateTo({
                  url: indexMessage + '/storeCard/storeCard',
                })
                that.setData({
                  addshow: false
                })
              }
            })
          } else {
            that.setData({
              showDeduct: true,
              addshow: false
            })
          }
        }
      })
    })
    that.setData({
      deductType: 'make'
    })
  },
  prepareScan: function() {
    var that = this;
    app.getUserInfo(function(personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      judgeVip.judgeVip(token, uid, function(result) {
        if (result) {
          that.scanCard();
          that.setData({
            addshow:false
          })
        } else {
          if (!that.data.holderdeduct) {
            that.scanCard();
          } else {
            that.setData({
              showDeduct: true,
              addshow: false
            })
          }
        }
      })
    })

    that.setData({
      deductType: 'scan'
    })
  },
  //扫描名片
  scanCard: function() {
    var that = this;
    this.privilege(function(result) {
      if (result) {
        wx.chooseImage({
          count: 1, // 默认9  
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有  
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
          success: function(res) {
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
            that.setData({
              src: res.tempFilePaths[0],
            })
            //提示
            wx.showLoading({
              title: '识别中稍等哦...',
            })
            app.getUserInfo(function(personInfo) {
              var token = personInfo.token;
              var openid = personInfo.openId;
              //请求token
              wx.request({
                url: port.CardOCRAuth, //请求地址
                header: { //请求头
                  "Content-Type": "applciation/json",
                  "Authorization": "Bearer " + token
                },
                data: {
                  openid: openid
                },
                method: "post", //get为默认方法/POST
                success: function(res) {
                  // 腾讯云ORC请求
                  wx.uploadFile({
                    url: 'https://recognition.image.myqcloud.com/ocr/businesscard',
                    filePath: that.data.src,
                    name: 'image',
                    header: { //请求头
                      "authorization": res.data.data.signStr,
                    },
                    formData: {
                      appid: res.data.data.appid,
                    },
                    method: "post",
                    success: function(res) {
                      wx.hideLoading()
                      var scanData = JSON.parse(res.data).result_list[0].data;
                      that.setData({
                        scanData: scanData,
                      })
                      if (scanData.length == 0) {
                        wx.showToast({
                          title: '扫描失败',
                          icon: 'none',
                        })
                      } else {
                        var dataStr = '?';
                        for (var i = 0; i < scanData.length; i++) {
                          dataStr += scanData[i].item + '=' + scanData[i].value + '&';
                        }
                        dataStr = dataStr.substring(0, dataStr.length - 1);
                        var indexMessage = that.data.indexMessage;
                        wx.navigateTo({
                          url: indexMessage + '/storeCard/storeCard' + dataStr,
                        })
                      }
                    },
                    fail: function(err) {},
                    complete: function(suc) {},
                  })
                },
                fail: function(err) {}, //请求失败
                complete: function(suc) { //请求完成后执行的函数
                }
              })
            })
          }
        })
      }
    })
  },
  privilege: function(backvip) {
    var that = this;
    app.getUserInfo(function(personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      vipPrivilege.vipPrivilege(token, uid, '', 'scanning', function(result) {
        if (result == 'vip-deficiency') { //VIP权限上限已达，但积分不足
          that.setData({
            tipknow: true,
            vipTipContent: '您今日添加名片的次数已用完，\n积分也不足咯~\n明天再来看吧~',
            addshow: false
          })
          return typeof backvip == "function" && backvip(false)
        } else if (result == 'deficiency') { //非会员，且积分不足
          that.setData({
            vipTip: true,
            vipTipContent: '您的积分不足喽~\n成为会员吧！\n获取更多特权，还有超多积分！',
            addshow: false
          })
          return typeof backvip == "function" && backvip(false)
        } else if (result == 'success') { //成功
          return typeof backvip == "function" && backvip(true)
        } else { //系统出错
          that.setData({
            addshow: false
          })
          wx.showToast({
            title: '查看失败，请重试',
          })
          return typeof backvip == "function" && backvip(false)
        }
      })
    })
  },
  // 获取搜索卡片夹内容
  searchInput: function(e) {
    this.data.searchInput = e.detail.value;
    this.showAll()
  },
  // 搜索卡片夹
  search: function() {
    this.showAll()
  },
  clickCards: function(e) {},
  //滑动收缩
  // touchMove: function () {
  // if(this.data.TopAddAlready == 1){
  // this.animate();
  // var choiceCard = this.data.choiceCard;
  // var personCards = this.data.personCards;
  // var personCardsLength = this.data.personCardsLength;
  // personCards[choiceCard - 1].animationJob = this.data.animationDataJobR;
  // personCards[choiceCard - 1].animationUserImg = this.data.animationDataUserImgR;
  // personCards[choiceCard - 1].zindexCard = 2 * choiceCard - 1;
  // for (var move = choiceCard; move < personCardsLength + 1; move++) {
  // personCards[move - 1].animation = this.data.animationData2;
  // personCards[move - 1].animation1 = this.data.animationData2;
  // personCards[move - 1].zindexCard = 2 * move - 1;
  // personCards[move - 1].zindexImg = 2 * move;
  // }
  // this.setData({
  // personCards: personCards,
  // TopAddAlready: 0
  // })
  // }
  // },


  showAll: function() {
    this.setData({
      cardNumCode: 1,
    })
    var that = this;
    var search = this.data.searchInput;
    app.getUserInfo(function(personInfo) {
      var openid = personInfo.openId;
      var token = personInfo.token;
      var uid = personInfo.uid;
      wx.showLoading({
        title: '努力加载中...',
      })
      that.setData({
        holderCheck: 1,
      })
      //上传、获取咖片集信息
      wx.request({
        url: port.FriendsList, //请求地址
        header: { //请求头
          "Content-Type": "applciation/json",
          "Authorization": "Bearer " + token
        },
        data: {
          'openid': openid,
          'search': search
        },
        method: "post", //get为默认方法/POST
        success: function(res) {
          if (res.data.status == 'success') {
            var cardPersonList = new Array()
            var personCards = new Array()
            if (res.data.data.length == 0) {
              that.setData({
                noBody: true
              })
              wx.hideLoading();
            } else {
              for (var i = 0; i < res.data.data.length; i++) {
                for (var j in res.data.data[i].card) {
                  if (res.data.data[i].card[j] == null) {
                    res.data.data[i].card[j] = "";
                  }
                }
                for (var j in res.data.data[i].user) {
                  if (res.data.data[i].user[j] == null) {
                    res.data.data[i].user[j] = "";
                  }
                }
              }
              for (var s in res.data.data) {
                var cardPersonObejct = new Object();
                cardPersonObejct.zimuModal = s;
                for (var i = 1; i < res.data.data[s].length + 1; i++) {

                  var dataTemp = res.data.data[s]
                  var personCardsO = new Object();
                  var cardNumCode = that.data.cardNumCode
                  personCardsO.cardId = dataTemp[i - 1].card.id;
                  // }

                  // var iconColor = dataTemp[i - 1].card.templet_sz.iconColor;
                  if (i == 1) {
                    personCardsO.id = s;
                    that.setData({
                      showZiMu: true
                    })
                  }

                  if (dataTemp[i - 1].card.avatar) {
                    personCardsO.img = port.imgPath + dataTemp[i - 1].card.avatar;
                  } else {
                    personCardsO.img = dataTemp[i - 1].card.avatar;
                  }

                  personCardsO.back = dataTemp[i - 1].card.templet_sz.smallBg;
                  personCardsO.name = dataTemp[i - 1].card.username;
                  personCardsO.job = dataTemp[i - 1].card.duty;
                  personCardsO.company = dataTemp[i - 1].card.company;
                  personCardsO.initial = dataTemp[i - 1].initial;
                  personCardsO.animateLeft = "";
                  personCardsO.animateRight = "";
                  personCardsO.is_paper = dataTemp[i - 1].is_paper;
                  personCardsO.friends_id = dataTemp[i - 1].friends_id;
                  if (i == 1) {
                    personCardsO.showZiMu = true;
                  } else {
                    personCardsO.showZiMu = false;
                  }
                  personCards.push(personCardsO);
                  cardNumCode++;
                  that.setData({
                    cardNumCode: cardNumCode,
                  })
                }
                cardPersonObejct.userList = personCards;
                cardPersonList.push(cardPersonObejct);
              }

              var noBody = false
              that.setData({
                personCards: personCards,
                cardPersonList: cardPersonList,
                noBody: noBody
              })
              wx.hideLoading();

              var holderCheck = wx.getStorage({
                key: 'holderCheck',
                success: function(res) {
                  if (res.data == 0) {
                    that.setData({
                      holderCheck: 0,
                      zSeaIndex: 50,
                      zIndex: 50,
                      whefixed: ''
                    })
                  } else if (res.data == 1) {
                    that.setData({
                      holderCheck: 1,
                    })
                  }
                },
              })
            }

          }
        },
        fail: function(err) {}, //请求失败
        complete: function(suc) { //请求完成后执行的函数
        }
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var that = this;
    var res = wx.getSystemInfoSync();
    var screenHeight = res.screenHeight;
    that.setData({
      screenHeight: screenHeight
    })
    app.getUserInfo(function(personInfo) {
      var token = personInfo.token;
      var uid = personInfo.uid;
      wx.request({
        url: port.CardMy, //请求地址
        header: { //请求头
          "Content-Type": "applciation/json",
          "Authorization": "Bearer " + token
        },
        data: {
          'uid': uid
        },
        method: "post", //get为默认方法/POST
        success: function(res) {
          if (res.data.status == 'success') {
            that.setData({
              cid: res.data.data.id
            })
          } else {}
        },
        fail: function(err) {
          wx.hideLoading()
        }, //请求失败
        complete: function(suc) { //请求完成后执行的函数
        }
      })
    })
  },
  choiceW: function(e) {
    let whiceGroup = e.target.id;
    this.setData({
      whiceGroup: whiceGroup
    })
  },
  // 滑动方向
  touchmove: function(e) {
    var touchId = e.currentTarget.dataset.aleftblock;
    var personCards = this.data.personCards;
    var currentX = e.touches[0].pageX
    var currentY = e.touches[0].pageY
    var tx = currentX - this.data.lastX
    var ty = currentY - this.data.lastY
    if (Math.abs(tx) > Math.abs(ty)) {
      if (tx < 0) {

        for (var i = 0; i < personCards.length; i++) {
          personCards[i].animate = "";
          personCards[i].animate1 = "";
        }
        personCards[touchId].animate = "removeEditALeft";
        personCards[touchId].animate1 = "NCJLeft";
        this.setData({
          touchId: touchId,
          personCards: personCards
        })

      } else
      if (tx > 0) {
        personCards[touchId].animate = "removeEditARight";
        personCards[touchId].animate1 = "NCJRight";
        this.setData({
          touchId: touchId,
          personCards: personCards
        })
      } else {

      }
    }
    //将当前坐标进行保存以进行下一次计算
    this.data.lastX = currentX
    this.data.lastY = currentY
  },
  animateR: function(e) {
    var clickId = e.currentTarget.dataset.aleftblock;
    var touchId = this.data.touchId;
    if (clickId == touchId) {

    } else {
      var personCards = this.data.personCards;
      personCards[touchId].animate = "removeEditARight";
      personCards[touchId].animate1 = "NCJRight"
      this.setData({
        personCards: personCards
      })
    }

  },
  // stopA:function(){
  //   var touchId = this.data.touchId;
  //   var personCards = this.data.personCards;
  //   personCards[touchId].animate = "removeEditARight";
  //   personCards[touchId].animate1 = "NCJRight"
  //   this.setData({
  //     personCards: personCards
  //   })
  // },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    that.showAll()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.showAll()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {}
})